import React, { Component, Fragment } from 'react';
import { Dispatch } from 'redux';
import { connect } from 'dva';

import router from 'umi/router';
import _ from 'lodash';
import qs from 'qs';

import { addTab } from '@/utils/utils';
import { Form } from '@ant-design/compatible';
import PageHeader from '@/components/PageHeader';
import { FormComponentProps } from '@ant-design/compatible/es/form';

import {
  Row,
  Col,
  Card,
  Table,
  Input,
  Button,
  Select,
} from 'antd';
import '@ant-design/compatible/assets/index.css';

const { Option } = Select;
const { Item } = Form;
const { pathname } = window.location;

interface CabinetDeliveryChargeListProps extends FormComponentProps {
  dispatch: Dispatch;
  loading: boolean;
  dataInfo: any;
  INITINFO: any;
  screen: string;
}

interface CabinetDeliveryChargeListState {
  searchValues: any;
  pageIndex: number;
  pageSize: number;
  rowId:number;
}

@connect(({
  CabinetDeliveryChargeList: { dataInfo },
  common: { INITINFO },
  loading,
  global: { screen },
}: any) => ({
  dataInfo,
  INITINFO,
  screen,
  loading: loading.effects['CabinetDeliveryChargeList/fetch'],
}))

class CabinetDeliveryChargeListElem extends Component<CabinetDeliveryChargeListProps,
CabinetDeliveryChargeListState> {
  columns = [
    {
      title: 'ID',
      dataIndex: 'id',
      width: 80,
    },
    {
      title: '快递员手机号',
      dataIndex: 'phone',
      width: 120,
    },
    {
      title: '快递公司',
      dataIndex: 'expressName',
      width: 120,
    },
    {
      title: '首次开通时间',
      dataIndex: 'createTime',
      width: 180,
    },
    {
      title: '操作',
      width: 80,
      render: (text: any, record: any) => (
        <div>
          <span
            className="operLink"
            onClick={() => this.handleRouterDetail(record)}
          >详情
          </span>
        </div>
      ),
    },
  ]

  state: CabinetDeliveryChargeListState = {
    searchValues: {},
    pageIndex: 1,
    pageSize: 20,
    rowId: 0,
  }

  static getDerivedStateFromProps(nextProps: any, preState: any) {
    const { location: { query } } = nextProps;
    const { pageIndex, pageSize, ...searchValues } = query;
    return {
      searchValues,
      pageIndex: Number(pageIndex) || 1,
      pageSize: Number(pageSize) || (nextProps.screen === 'sm' ? 100 : 20),
    };
  }

  componentDidMount() {
    this.setFieldsValue();

    const { dataInfo } = this.props;
    if (dataInfo?.list?.length) return;

    this.fetchDataValues();
    this.fetchAction('common/fetchExpressList');
  }

  componentDidUpdate(prevProps: any, prevState: any) {
    const { searchValues, pageIndex, pageSize } = this.state;
    if (!_.isEqual(searchValues, prevState.searchValues)
      || pageIndex !== prevState.pageIndex
      || pageSize !== prevState.pageSize) {
      this.setFieldsValue();
      this.fetchDataValues();
    }
  }

  setFieldsValue = () => { // 设置表单
    const { searchValues } = this.state;
    const { form: { setFieldsValue } } = this.props;
    setFieldsValue(searchValues);
  }

  fetchDataValues = () => this.fetchAction('fetch', this.getQueryParams());

  getQueryParams = () => {
    const { searchValues, pageIndex, pageSize } = this.state;
    const params = {
      ...searchValues,
      pageIndex,
      pageSize,
    };
    return params;
  }

  handleRouterDetail = (record: any) => {
    const { dispatch } = this.props;
    addTab(dispatch, {
      name: `查看${record.uid}`,
      url: `/charges/cabinetDeliveryCharge/list/detail?uid=${record.uid}`,
    });
  }

  handleSearch = (e: React.FormEvent) => {
    e.preventDefault();

    const { form: { validateFields } } = this.props;
    validateFields((errors, values) => {
      if (errors) return;

      const query = {
        ...values,
        pageIndex: 1,
        pageSize: 20,
      };

      const { dispatch } = this.props;
      addTab(dispatch, {
        name: '柜体寄件资费配置',
        url: `${pathname}?${qs.stringify(query)}`,
        isTopMenu: true,
      });
    });
  }

  handleReset = () => {
    const { form: { resetFields } } = this.props;
    resetFields();

    const { dispatch } = this.props;
    addTab(dispatch, {
      name: '柜体寄件资费配置',
      url: pathname,
      isTopMenu: true,
    });
  }

  onSelectChange = (pageIndex: number, pageSize: number) => {
    const { searchValues } = this.state;
    const query = { ...searchValues, pageIndex, pageSize };

    const { dispatch } = this.props;
    addTab(dispatch, {
      name: '柜体寄件资费配置',
      url: `${pathname}?${qs.stringify(query)}`,
      isTopMenu: true,
    });
  }

  handleRoute = (routePath: string, query?: object) => {
    router.push({
      pathname: routePath,
      query,
    });
  }

  onClickRow = ({ id }: any) => ({
    onClick: () => {
      this.setState({ rowId: id });
    },
  })

  setRowClassName = ({ id }: any) => {
    const { rowId } = this.state;
    return id === rowId ? 'clickRowStyl' : '';
  }

  fetchAction = (typeName: string, payload: any = {}) => {
    const type = typeName.indexOf('common') >= 0
      ? typeName : `CabinetDeliveryChargeList/${typeName}`;
    const { dispatch } = this.props;
    dispatch({ type, payload });
  }

  render() {
    const {
      pageIndex,
      pageSize,
    } = this.state;
    const {
      form: { getFieldDecorator },
      INITINFO: { expressList },
      dataInfo,
      loading,
    } = this.props;

    const dataSource = dataInfo ? dataInfo.list : [];
    const pagination: object = dataInfo
      ? {
        total: dataInfo.count,
        current: pageIndex,
        pageSize,
        showQuickJumper: true,
        showSizeChanger: true,
        pageSizeOptions: ['10', '20', '50', '100'],
        showTotal: () => `共${dataInfo.count || 0}条数据`,
        onChange: this.onSelectChange,
        onShowSizeChange: this.onSelectChange,
      }
      : {};

    return (
      <Fragment>
        <PageHeader />

        <Card bordered={false} className="searchForm">
          <Form className="tableListForm" onSubmit={this.handleSearch}>
            <Row gutter={12}>
              <Col md={6} sm={24}>
                <Item label="快递员手机号" colon={false}>
                  {getFieldDecorator('phone')(
                    <Input allowClear type="number" placeholder="请输入" />,
                  )}
                </Item>
              </Col>
              <Col md={6} sm={24}>
                <Item label="　　快递公司" colon={false}>
                  {getFieldDecorator('expressId')(
                    <Select
                      showSearch
                      allowClear
                      placeholder="请选择"
                      filterOption={(input: any, option: any) => (
                        option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
                      )}
                    >
                      {expressList.reverse().map((item: any) => (
                        <Option value={String(item.id)} key={item.id}>{item.name}</Option>
                      ))}
                    </Select>,
                  )}
                </Item>
              </Col>
              <Col md={12} sm={24}>
                <div className="flexFeView">
                  <Button
                    type="primary"
                    htmlType="submit"
                    className="smallButton"
                  >
                    查询
                  </Button>
                  <Button
                    className="addButton marginL16 smallButton"
                    type="primary"
                    onClick={this.handleReset}
                  >重置
                  </Button>
                </div>
              </Col>
            </Row>
          </Form>
        </Card>

        <Card bordered={false} className="tableList">
          <Table
            rowKey="id"
            tableLayout="fixed"
            className="statementTable tableHeight60"
            columns={this.columns}
            dataSource={dataSource}
            pagination={pagination}
            loading={loading}
            scroll={{ x: 780 }}
            onRow={this.onClickRow}
            rowClassName={this.setRowClassName}
          />
        </Card>
      </Fragment>
    );
  }
}

export default Form.create<CabinetDeliveryChargeListProps>()(CabinetDeliveryChargeListElem);
